package com.zhiwang.planet.mvvm.binding;

import android.animation.ValueAnimator;
import android.view.View;

import androidx.databinding.BindingAdapter;
import androidx.databinding.InverseBindingAdapter;
import androidx.databinding.InverseBindingListener;
import androidx.databinding.InverseBindingMethod;
import androidx.databinding.InverseBindingMethods;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.SetTabCallBack;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


@InverseBindingMethods({
        @InverseBindingMethod(
                type = CommonTabLayout.class,
                attribute = "tabActive")
})


public class CommonTabLayoutBindingAdapter {


    @InverseBindingAdapter(attribute = "tabActive", event = "tabActiveAttrChanged")
    public static boolean getMainTabActive(CommonTabLayout tabLayout) {
        return tabLayout.getCurrentTab() == 0;
    }

    @BindingAdapter(value = {"tabActiveAttrChanged"}, requireAll = false)
    public static void setMainTabActiveListener(CommonTabLayout tabLayout, InverseBindingListener listener) {
        //no op

        //以下两种方式都可以，后一种动态代理更方便
//        if (listener == null)
//            tabLayout.setOnTabSetListener(cb);
//        else
//            tabLayout.setOnTabSetListener(new CommonTabLayout.OnTabSet() {
//                @Override
//                public void onTabSet(int position) {
//                    if (cb != null)
//                        cb.onTabSet(position);
//                    listener.onChange();
//                }
//            });
        Proxy.newProxyInstance(CommonTabLayout.class.getClassLoader(), new Class[]{CommonTabLayout.class}, new MainTabProxy(listener, tabLayout));
    }

    @BindingAdapter("tabActive")
    public void setTabActive(CommonTabLayout tabLayout, boolean active) {
//        tabLayout.setCurrentTab(active);
    }


    static class MainTabProxy implements InvocationHandler {

        InverseBindingListener listener;
        CommonTabLayout tabLayout;

        public MainTabProxy(InverseBindingListener listener, CommonTabLayout tabLayout) {
            this.listener = listener;
            this.tabLayout = tabLayout;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("setCurrentTab")) {
                listener.onChange();
            }
            return method.invoke(tabLayout, args);
        }
    }

}

